package cn.zhangfusheng.elasticsearch.jexl.analysis.impl;

import cn.zhangfusheng.elasticsearch.jexl.Jexl3Execute;
import cn.zhangfusheng.elasticsearch.jexl.Jexl3Util;
import cn.zhangfusheng.elasticsearch.jexl.analysis.Analysis;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * if 表达式
 * @author fusheng.zhang
 * @date 2022-03-05 16:24:15
 */
@Data
public class IfElseAnalysis implements Analysis {

    /**
     * if条件语句 ()
     */
    private String ifCondition;

    private String ifExecute;

    private List<Analysis> ifAnalyses;

    private String elseExecute;

    private List<Analysis> elseAnalyses;

    @Override
    public String toString() {
        StringBuilder str = new StringBuilder();
        if (Objects.nonNull(ifCondition)) {
            str.append("if(").append(ifCondition).append(")").append("{");
            if (Objects.nonNull(ifExecute)) {
                str.append(ifExecute);
            }
            if (Objects.nonNull(ifAnalyses)) {
                ifAnalyses.forEach(analysis -> str.append(analysis.toString()));
            }
            str.append("}");
            if (Objects.nonNull(elseExecute)) {
                str.append(" else {").append(elseExecute).append("}");
            }
            if (Objects.nonNull(elseAnalyses)) {
                str.append(" else {");
                elseAnalyses.forEach(analysis -> str.append(analysis.toString()));
                str.append("}");
            }
        }
        return str.toString();
    }

    @Override
    public void execute(Jexl3Execute jexl3Execute) {
        Object o = Jexl3Util.execute(jexl3Execute.getParams(), jexl3Execute.getConstantParams(), Jexl3Util.toStr(ifCondition));
        if (Objects.nonNull(o) && Boolean.parseBoolean(o.toString())) {
            if (StringUtils.isNotBlank(ifExecute)) jexl3Execute.setStr(ifExecute);
            if (!CollectionUtils.isEmpty(ifAnalyses)) {
                ifAnalyses.forEach(analysis -> analysis.execute(jexl3Execute));
            }
        } else {
            if (StringUtils.isNotBlank(elseExecute)) jexl3Execute.setStr(elseExecute);
            if (!CollectionUtils.isEmpty(elseAnalyses)) {
                elseAnalyses.forEach(analysis -> analysis.execute(jexl3Execute));
            }
        }
    }
}

